<template>
	<view class="vip-page">
		<!-- 导航栏 -->
		<u-navbar  bgColor="transparent" title="会员卡" leftIconColor="#fff" titleStyle="color:#fff" :autoBack="true"></u-navbar>
		
		<!-- 会员卡片区域 -->
		<view class="member-card-section">
			
		</view>
		<view class="" style="padding: 0rpx 30rpx;" >
			<view class="member-card">
				<!-- 背景图片 -->
				<image 
					src="/static/my/vip_bg.png" 
					mode="aspectFill" 
					class="card-bg-image"
				></image>
				
				<view class="card-header" v-if="Userinfo.vip" >
					<view class="user-info">
						<view class="greeting">尊贵的会员您好！</view>
						<view class="user-name">
							<image :src="Userinfo.avatar?Userinfo.avatar:'/static/logo.png'" mode="aspectFill" class="user-avatar"></image>
							<text class="name-text">{{Userinfo.nickname}}</text>
						</view>
					</view>
					<view class="expire-info">
						<text class="expire-text">{{Userinfo.vipDeadline}}过期</text>
					</view>
				</view>
				<view class="card-header" v-else >
					<view class="user-info">
						<view class="greeting">您还未开通会员！</view>
						<view class="user-name">
							<image :src="Userinfo.avatar?Userinfo.avatar:'/static/logo.png'" mode="aspectFill" class="user-avatar"></image>
							<text class="name-text">{{Userinfo.nickname}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 会员套餐选择 -->
		<view class="package-section">
			<view class="section-title">
				<view class="title-line"></view>
				<text class="title-text">会员套餐</text>
			</view>
			
			<view class="package-list">
				<view 
					class="package-item" 
					v-for="(item, index) in packageList" 
					:key="index"
					:class="{ 'active': selectedPackage === index }"
					@click="selectPackage(index)"
				>
					<view class="package-content">
						<view class="package-duration">{{ item.duration }}</view>
						<view class="package-price">
							<text class="currency">￥</text>
							<text class="amount">{{ item.price }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 购买按钮 -->
		<view class="purchase-section" >
			<view class="purchase-btn" @click="handlePurchase">
				<text class="btn-text">{{Userinfo.vip?'立即续费':'立即开通'}}</text>
			</view>
		</view>
		
		<!-- 支付方式弹出框 -->
		<PaymentPop 
			:show="paymentPopupShow"
			:mini="true"
			:balance="false"
			:price="currentVipPrice" 
			@close="paymentPopupShow = false"
			@confirm="handlePaymentConfirm" 
		/>
	</view>
</template>

<script>
	import { getVipList, rechargeVip } from '@/api/user.js'
	import PaymentPop from '@/components/PaymentPop.vue'
	import store from '@/store/index.js'
	
	export default {
		components: {
			PaymentPop
		},
		data() {
			return {
				selectedPackage: 0, // 默认选中第一个套餐
				packageList: [], // 会员套餐列表
				userVipInfo: null, // 用户会员信息
				paymentPopupShow: false, // 支付弹窗显示状态
				currentVipPrice: '0.00', // 当前选择的VIP价格
				currentVipPackage: null // 当前选择的VIP套餐
			}
		},
		computed: {
			Userinfo() {
				this.userinfo = this.$store.state.userinfo;
				return this.$store.state.userinfo;
			}
		},
		onLoad() {
			// 页面加载时获取会员套餐数据
			this.loadVipPackages()
		},
		methods: {
			// 加载会员套餐数据
			loadVipPackages() {
				uni.showLoading({
					title: '加载中...'
				});
				
				getVipList().then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						// 格式化套餐数据
						this.packageList = this.formatVipPackages(res.data || []);
						console.log('会员套餐数据:', this.packageList);
					} else {
						uni.showToast({
							title: res.msg || '获取会员套餐失败',
							icon: 'none'
						});
						// 使用默认数据
						this.loadDefaultPackages();
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取会员套餐失败:', err);
					uni.showToast({
						title: '获取会员套餐失败',
						icon: 'none'
					});
					// 使用默认数据
					this.loadDefaultPackages();
				});
			},
			
			// 格式化会员套餐数据
			formatVipPackages(packages) {
				return packages.map(item => ({
					id: item.id,
					duration: this.formatDuration(item.validTime), // 使用validTime字段作为时长
					price: item.price.toString(),
					originalPrice: item.originalPrice ? item.originalPrice.toString() : '',
					description: item.description || '',
					benefits: item.benefits || [],
					// 原始数据
					originalData: item
				}));
			},
			
			// 格式化时长显示（处理validTime字段）
			formatDuration(validTime) {
				if (typeof validTime === 'number') {
					// 如果是数字，按月份处理
					if (validTime === 1) {
						return '1个月';
					} else if (validTime === 3) {
						return '3个月';
					} else if (validTime === 6) {
						return '6个月';
					} else if (validTime === 12) {
						return '1年';
					} else {
						return `${validTime}个月`;
					}
				}
				return validTime || '1个月';
			},
			
			// 加载默认套餐数据（备用）
			loadDefaultPackages() {
				this.packageList = [];
			},
			
			// 选择套餐
			selectPackage(index) {
				this.selectedPackage = index;
			},
			
			// 处理购买
			handlePurchase() {
				if (this.packageList.length === 0) {
					uni.showToast({
						title: '暂无可用套餐',
						icon: 'none'
					});
					return;
				}
				
				const selectedPkg = this.packageList[this.selectedPackage];
				this.currentVipPackage = selectedPkg;
				this.currentVipPrice = selectedPkg.price;
				this.paymentPopupShow = true;
			},
			
			// 处理支付确认
			handlePaymentConfirm(payment) {
				console.log('选择的支付方式:', payment);
				this.processVipPayment(this.currentVipPackage, payment);
			},
			
			// 处理VIP支付
			processVipPayment(packageInfo, payment) {
				
				// 调用开通会员接口
				rechargeVip({
					vipId: packageInfo.id,
					payType:payment.paytype
				}).then(res => {
					if (res.code == 200) {
						// 关闭支付弹窗
						this.paymentPopupShow = false;
						let paydata=JSON.parse(res.data);
						this.payment(paydata);
					} 
				})
			},
			payment(data) {
				console.log(data,'++++=')
				let that = this;
				uni.requestPayment({
					"provider": "wxpay", //固定值为"wxpay"
					"timeStamp": data.timeStamp,
					"nonceStr": data.nonceStr,
					"package": data.packageValue,
					"signType": data.signType,
					"paySign": data.paySign,
					success: function(res) {
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #F7F7F7;
	}

	.vip-page {
		min-height: 100vh;
		background-color: #F7F7F7;
		padding-bottom: 100rpx;
	}

	// 会员卡片区域
	.member-card-section {
		background: linear-gradient(135deg, #4E5166 0%, #1E212F 100%);
		padding: 20rpx 20rpx 100rpx;
		border-radius: 0 0 100rpx 100rpx;
		position: relative;
		height: 400rpx;
		
		
	}
	.member-card {
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		position: relative;
		overflow: hidden;
		margin-top: -150rpx;
		
		.card-bg-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
		}
		
		.card-header {
			position: relative;
			z-index: 2;
			
			.user-info {
				margin-bottom: 20rpx;
				
				.greeting {
					color: #A66E1F;
					font-size: 30rpx;
					margin-bottom: 20rpx;
				}
				
				.user-name {
					display: flex;
					align-items: center;
					
					.user-avatar {
						width: 72rpx;
						height: 72rpx;
						border-radius: 50%;
						margin-right: 20rpx;
					}
					
					.name-text {
						color: #A66E1F;
						font-size: 30rpx;
						font-weight: 500;
					}
				}
			}
			
			.expire-info {
				position: absolute;
				right: 30rpx;
				bottom: 0rpx;
				
				.expire-text {
					color: #A66E1F;
					font-size: 24rpx;
				}
			}
		}
	}

	// 套餐选择区域
	.package-section {
		padding: 0 30rpx;
		margin-top: 40rpx;
		
		.section-title {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			
			.title-line {
				width: 6rpx;
				height: 30rpx;
				background-color: #FFD477;
				margin-right: 20rpx;
			}
			
			.title-text {
				color: #333333;
				font-size: 30rpx;
				font-weight: 500;
			}
		}
		
		.package-list {
			display: flex;
			justify-content: space-between;
			gap: 10rpx;
			
			.package-item {
				width: 240rpx;
				height: 240rpx;
				background-color: #FFFFFF;
				border: 2rpx solid #EBEBEB;
				border-radius: 10rpx;
				padding: 0;
				text-align: center;
				box-shadow: 0 0 12rpx rgba(153, 153, 153, 0.16);
				transition: all 0.3s ease;
				position: relative;
				
				&.active {
					border-color: #FFCF78;
					background-color: #FEFBF6;
					
					.package-duration {
						color: #875E2B;
					}
					
					.package-price {
						.currency, .amount {
							color: #875E2B;
						}
					}
				}
				
				.package-content {
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					
					.package-duration {
						color: #333333;
						font-size: 32rpx;
						margin-bottom: 20rpx;
						font-weight: 500;
					}
					
					.package-price {
						display: flex;
						align-items: baseline;
						justify-content: center;
						
						.currency {
							color: #333333;
							font-size: 28rpx;
							margin-right: 4rpx;
						}
						
						.amount {
							color: #333333;
							font-size: 52rpx;
							font-weight: 500;
						}
					}
				}
			}
		}
	}

	// 购买按钮区域
	.purchase-section {
		padding: 40rpx 30rpx;
		
		.purchase-btn {
			background: linear-gradient(90deg, #F6D9AF 0%, #C49A4F 100%);
			border-radius: 8rpx;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.btn-text {
				color: #A66E1F;
				font-size: 30rpx;
				font-weight: 500;
			}
		}
	}
</style>
